package lu.med.praxiswahl.wahlumed.dao.beans;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import lu.med.praxiswahl.wahlumed.dao.beans.daointerface.CashBookDAOInt;
import lu.med.praxiswahl.wahlumed.model.beans.CashBookTBL;

/**
 * Session Bean implementation class CashBookDAO
 */
@Stateless
public class CashBookDAO implements CashBookDAOInt {
	@PersistenceContext(unitName = "gynaekomedic-ejbPU")
	private EntityManager em = null;

	/**
	 * Default constructor.
	 */
	public CashBookDAO() {
	}

	@Override
	public void delete(Long obj) {
		CashBookTBL entry = em.find(CashBookTBL.class, obj);

		em.remove(entry);
		em.flush();

	}

	@Override
	public void persist(CashBookTBL obj) {
		Calendar savedTime = new GregorianCalendar();
		obj.getDatum().set(Calendar.AM_PM, savedTime.get(Calendar.AM_PM));
		obj.setLineNumber(this.retrieveNextLineNumber(
				obj.getDatum().get(Calendar.YEAR),
				obj.getDatum().get(Calendar.MONTH) + 1));

		em.persist(obj);
		em.flush();

	}

	@Override
	public int retrieveNextLineNumber(int year, int month) {
		String parsedStringMonthValue = "" + month;

		if (parsedStringMonthValue.length() == 1) {
			parsedStringMonthValue = "0" + month;
			try {
				Integer result = (Integer) em.createQuery(
						"select max(c.lineNumber) from CashBookTBL c where c.datum like '"
								+ year + "-" + parsedStringMonthValue + "-%'")
						.getSingleResult();

				if (result == null) {
					return 1;
				} else {
					return result.intValue() + 1;
				}

			} catch (Exception e) {
				throw new RuntimeException(
						"Could not retrieve line number by year and month", e);
			}
		} else {

			try {
				Integer result = (Integer) em.createQuery(
						"select max(c.lineNumber) from CashBookTBL c where c.datum like '"
								+ year + "-" + parsedStringMonthValue + "-%'")
						.getSingleResult();

				if (result == null) {
					return 1;
				} else {
					return result.intValue() + 1;
				}
			} catch (Exception e) {
				throw new RuntimeException(
						"Could not retrieve line number by year and month", e);
			}
		}
	}

	@Override
	public CashBookTBL retrieveCashBookEntryByID(Long id) {
		return em.find(CashBookTBL.class, id);
	}

	@Override
	public List<CashBookTBL> retrieveCashBookEntryByYear(String year) {
		// TODO Auto-generated method stub
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<CashBookTBL> retrieveCashBookEntryByYearAndMonth(int year,
			int month) {
		String parsedStringMonthValue = "" + month;

		if (parsedStringMonthValue.length() == 1) {
			parsedStringMonthValue = "0" + month;

			try {
				return this.reoderCashBookEntries((List<CashBookTBL>) em
						.createQuery(
								"select c from CashBookTBL c where c.datum like '"
										+ year + "-" + parsedStringMonthValue
										+ "-%' order by c.datum asc")
						.getResultList());
			} catch (Exception e) {
				return null;
				// throw new RuntimeException(
				// "Could not retrieve cash book entries by year and month",
				// e);
			}

		} else {

			try {
				return this.reoderCashBookEntries((List<CashBookTBL>) em
						.createQuery(
								"select c from CashBookTBL c where c.datum like '"
										+ year + "-" + parsedStringMonthValue
										+ "-%' order by c.datum asc")
						.getResultList());
			} catch (Exception e) {
				throw new RuntimeException(
						"Could not retrieve cash book entries by year and month",
						e);
			}
		}

	}

	@Override
	public void update(CashBookTBL obj) {
		Calendar savedTime = new GregorianCalendar();
		obj.getDatum().set(Calendar.AM_PM, savedTime.get(Calendar.AM_PM));
		em.merge(obj);
		em.flush();

	}

	@Override
	public List<CashBookTBL> reoderCashBookEntries(List<CashBookTBL> list) {
		List<CashBookTBL> listTmp = new ArrayList<CashBookTBL>();

		for (int i = 0; i < list.size(); i++) {
			listTmp.add(list.get(i));
		}

		for (int i = 0; i < list.size(); i++) {

			if (list.get(i).getEvent() != null) {
				if (list.get(i).getEvent().equals("ANFANG-BESTAND") && i != 0) {
					listTmp.remove(i);
					listTmp.add(0, list.get(i));
					// return list;
				}
			}
		}
		return listTmp;
	}

	@Override
	public CashBookTBL retrieveCashBookEntryByBillNumber(long billNumber) {
		try {
			return (CashBookTBL) em.createQuery(
					"select c from CashBookTBL c where c.billId = '"
							+ billNumber + "'").getSingleResult();
		} catch (Exception e) {
			return null;
			// throw new RuntimeException(
			// "Could not retrieve cash book bill entry",
			// e);

		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<CashBookTBL> retrieveCashBookEntryByYearAndMonth(int year,
			int month, boolean cashEntries) {
		String parsedStringMonthValue = "" + month;

		if (parsedStringMonthValue.length() == 1) {
			parsedStringMonthValue = "0" + month;
			
			try {
				return this.reoderCashBookEntries((List<CashBookTBL>) em
						.createQuery(
								"select c from CashBookTBL c where c.datum like '"
										+ year + "-" + parsedStringMonthValue
										+ "-%'" + "and cash = " + cashEntries
										+ " order by c.datum asc")
						.getResultList());
			} catch (Exception e) {
				return null;
				// throw new RuntimeException(
				// "Could not retrieve cash book entries by year and month",
				// e);
			}

		} else {
			
			try {
				return this.reoderCashBookEntries((List<CashBookTBL>) em
						.createQuery(
								"select c from CashBookTBL c where c.datum like '"
										+ year + "-" + parsedStringMonthValue
										+ "-%'" + "and cash = " + cashEntries
										+ " order by c.datum asc")
						.getResultList());
			} catch (Exception e) {
				return null;
//				throw new RuntimeException(
//						"Could not retrieve cash book entries by year and month",
//						e);
			}
		}

	}

}
